import { defineStore } from 'pinia';
import { 
  getUserInfo, 
  saveUserInfo, 
  updateUserInfo, 
  getUserToken, 
  saveUserToken, 
  clearUserToken, 
  clearUserInfo 
} from "@/utils/cache";

interface UserState {
  token: string | null;
  userInfo: any;
  email: string;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getUserToken() || null,
    userInfo: getUserInfo() || {},
    email: getUserInfo()?.email || '',
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token
  },
  
  actions: {
    setUserInfo(value: any) {
      this.userInfo = value;
      saveUserInfo(value);
    },
    
    setToken(token: string) {
      this.token = token;
      saveUserToken(token);
    },

    setEmail(email: string) {
      this.email = email;
      // 更新用户信息的一部分
      updateUserInfo({ email });
    },
    
    logout() {
      this.token = null;
      this.userInfo = {};
      this.email = '';
      // 直接使用新系统的清除函数
      clearUserToken();
      clearUserInfo();
    }
  },

  persist: {
    key: 'user', // 存储名称
    storage: 'localStorage', // 存储方式
    paths: ['userInfo', 'token'],
  }
}); 